﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using log4net;
using log4net.Core;

namespace Aribaccio.Logger
{
    public class LoggerWriter
    {
        /// <summary>
        /// 默认日志存储操作对象
        /// </summary>
        protected ILogger DefaultLogger { get; set; }
        /// <summary>
        /// 调试日志存储操作对象
        /// </summary>
        protected ILogger DebugLogger { get; set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        public LoggerWriter()
        {
            this.DefaultLogger = LoggerManager.GetLogger(Assembly.GetExecutingAssembly(), "DefaultLogger");
            this.DebugLogger = LoggerManager.GetLogger(Assembly.GetExecutingAssembly(), "DebugLogger");
        }

        /// <summary>
        /// 刷新数据
        /// </summary>
        /// <param name="argMillisecondsTimeout"></param>
        /// <returns></returns>
        public bool Flush(int argMillisecondsTimeout = 1000)
        {
            return LogManager.Flush(argMillisecondsTimeout);
        }

        /// <summary>
        /// 写入日志消息
        /// </summary>
        /// <param name="argLoggerMsg">日志消息对象</param>
        public void WriteLogMsg(LoggerMsg argLoggerMsg)
        {
            if (!this.DefaultLogger.IsEnabledFor(argLoggerMsg.MsgLevel)) return;

            string strLogMsg = this.ParseLogMsgFormatString(argLoggerMsg);
            if (argLoggerMsg.MsgLevel == Level.Debug)
            {
                this.DebugLogger.Log(typeof(LoggerWriter), argLoggerMsg.MsgLevel, strLogMsg, argLoggerMsg.MsgException);
            }
            else
            {
                this.DefaultLogger.Log(typeof(LoggerWriter), argLoggerMsg.MsgLevel, strLogMsg, argLoggerMsg.MsgException);
            }
        }

        /// <summary>
        /// 解析格式化日志字符串
        /// </summary>
        /// <param name="argLoggerMsg">日志消息对象</param>
        /// <returns></returns>
        protected string ParseLogMsgFormatString(LoggerMsg argLoggerMsg)
        {
            string dtFormat = !string.IsNullOrWhiteSpace(argLoggerMsg.MsgDateTimeFormat)
                ? argLoggerMsg.MsgDateTimeFormat
                : "HH:mm:ss.fff";
            string strDateTime = argLoggerMsg.MsgDateTime.ToString(dtFormat);
            return $"{strDateTime}  [{argLoggerMsg.MsgLevel.Name}]\t{argLoggerMsg.Message}";
        }

    }
}
